<template>
  <div class="box">
    <vxe-toolbar>
      <template #buttons>
        <vxe-button
          status="success"
          icon="vxe-icon-square-plus"
          @click="insertEvent()"
          >新增</vxe-button
        >
      </template>
    </vxe-toolbar>
    <p>
      教练姓名<vxe-input
        v-model="filterName"
        type="search"
        placeholder="试试全表搜索"
        @keyup="searchEvent"
      ></vxe-input>
    </p>
    <vxe-table
      border
      class="mytable-scrollbar"
      show-footer
      stripe
      ref="xTable"
      height="400"
      :column-config="{ resizable: true }"
      :row-config="{ isHover: true }"
      :data="list"
      @cell-dblclick="cellDBLClickEvent"
    >
      <vxe-column type="seq" title="序号" width="150"></vxe-column>
      <vxe-column
        field="name"
        title="教练姓名"
        fixed="left"
        width="100"
      ></vxe-column>
      <!-- <vxe-column field="sex" title="Sex" :formatter="formatterSex"></vxe-column> -->
      <vxe-column field="phone" title="手机号码" width="150"></vxe-column>
      <vxe-column field="object" title="教学科目" width="150"></vxe-column>
      <vxe-column field="schoolName" title="所在校区" width="150"></vxe-column>
      <vxe-column
        field="level"
        title="教练等级"
        :filters="levelOptions"
        :formatter="formatterLevel"
        width="150"
      ></vxe-column>
      <vxe-column field="time" title="入职日期" width="150"></vxe-column>
      <!-- 学员 -->
      <vxe-column field="students" width="150" title="学员">
        <template #default="{ row }">
          <vxe-button
            type="text"
            class="stubutton"
            icon="vxe-icon-user"
            @click="handleDetail(row)"
            >查看学员</vxe-button
          >
        </template>

        <!-- <stuButton/> -->
      </vxe-column>

      <vxe-column title="操作" width="150" fixed="right" show-overflow>
        <template #default="{ row }">
          <vxe-button type="text" icon="vxe-icon-edit" @click="editEvent(row)"
            >编辑</vxe-button
          >
          <vxe-button
            type="text"
            icon="vxe-icon-delete"
            @click="removeEvent(row)"
            >删除</vxe-button
          >
        </template>
      </vxe-column>
    </vxe-table>

    <vxe-modal
      v-model="showEdit"
      :title="selectRow ? '编辑&保存' : '新增&保存'"
      width="800"
      min-width="600"
      min-height="300"
      resize
      destroy-on-close
    >
      <template #default>
        <vxe-form
          :data="formData"
          :rules="formRules"
          title-align="right"
          title-width="100"
          @submit="submitEvent"
        >
          <vxe-form-item
            title="教练信息"
            title-align="left"
            :title-width="150"
            :span="24"
            :title-prefix="{ icon: 'vxe-icon-comment' }"
          ></vxe-form-item>
          <vxe-form-item
            field="name"
            title="教练姓名"
            :span="12"
            :item-render="{}"
          >
            <template #default="{ data }">
              <vxe-input
                v-model="data.name"
                placeholder="请输入名称"
              ></vxe-input>
            </template>
          </vxe-form-item>
          <vxe-form-item
            field="phone"
            title="手机号码"
            :span="12"
            :item-render="{}"
          >
            <template #default="{ data }">
              <vxe-input
                v-model="data.phone"
                placeholder="请输入名称"
              ></vxe-input>
            </template>
          </vxe-form-item>

          <vxe-form-item
            field="schoolName"
            title="所在校区"
            :span="12"
            :item-render="{}"
          >
            <template #default="{ data }">
              <vxe-select
                v-model="data.schoolName"
                transfer
                placeholder="选择校区"
              >
                <vxe-option
                  v-for="item in schoolList"
                  :key="item.objectId"
                  :value="item.schoolName"
                  :label="item.schoolName"
                ></vxe-option>
              </vxe-select>
            </template>
          </vxe-form-item>

          <vxe-form-item
            title="培训信息"
            title-align="left"
            :title-width="150"
            :span="24"
            :title-prefix="{
              message: '请填写必填项',
              icon: 'vxe-icon-info-circle-fill',
            }"
          >
          </vxe-form-item>
          <vxe-form-item
            field="object"
            title="教学科目"
            :span="12"
            :item-render="{}"
          >
            <template #default="{ data }">
              <vxe-select v-model="data.object" transfer placeholder="选择科目">
                <vxe-option
                  v-for="item in objectList"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                ></vxe-option>
              </vxe-select>
            </template>
          </vxe-form-item>
          <vxe-form-item
            field="level"
            title="等级"
            :span="12"
            :item-render="{}"
          >
            <template #default="{ data }">
              <vxe-select v-model="data.level" transfer placeholder="教练等级">
                <vxe-option
                  v-for="item in levelList"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                ></vxe-option>
              </vxe-select>
            </template>
          </vxe-form-item>
          <vxe-form-item
            field="time"
            title="入职日期"
            :span="12"
            :item-render="{}"
          >
            <template #default="{ data }">
              <vxe-input
                v-model="data.time"
                type="date"
                placeholder="请选择日期"
                transfer
              ></vxe-input>
            </template>
          </vxe-form-item>
          <vxe-form-item
            field="carType"
            title="车辆类型"
            :span="12"
            :item-render="{}"
          >
            <template #default="{ data }">
              <vxe-select
                v-model="data.carType"
                transfer
                placeholder="车辆类型"
              >
                <vxe-option
                  v-for="item in carList"
                  :key="item.objectId"
                  :value="item.carType"
                  :label="item.carType"
                ></vxe-option>
              </vxe-select>
            </template>
          </vxe-form-item>
          <vxe-form-item
            field="coachintro"
            title="教练简介"
            :span="24"
            :item-render="{}"
            :title-suffix="{
              message: '提示信息！！',
              icon: 'vxe-icon-question-circle-fill',
            }"
          >
            <template #default="{ data }">
              <vxe-textarea
                v-model="data.coachintro"
                :autosize="{ minRows: 2, maxRows: 4 }"
                placeholder="请输入教练简介内容"
              ></vxe-textarea>
            </template>
          </vxe-form-item>

          <vxe-form-item align="center" title-align="left" :span="24">
            <template #default>
              <vxe-button type="submit">提交</vxe-button>
              <vxe-button type="reset">重置</vxe-button>
            </template>
          </vxe-form-item>
        </vxe-form>
      </template>
    </vxe-modal>
    <vxe-modal
      v-model="stuShow"
      :title="'授课学员'"
      width="1100"
      height="650"
      min-width="600"
      min-height="300"
      resize
      destroy-on-close
    >
      <template #default>
        <p class="title"><span class="borderleft"></span>教练训练学员</p>
        
        <div style="margin-top: 30px">
          <vxe-table border height="400" :data="stuList">
            <vxe-column type="seq" width="60"></vxe-column>
            <vxe-column field="name" title="学员姓名"></vxe-column>
            <vxe-column field="tel" title="联系方式"></vxe-column>
            <vxe-column field="subject" title="当前科目"></vxe-column>
            <vxe-column field="subjectState " title="当前进度"></vxe-column>
            <vxe-column field="progressTime" title="进度时间"></vxe-column>
            <vxe-column field="count" title="考试次数"></vxe-column>
            <vxe-column field="passTime" title="合格时间"></vxe-column>
          </vxe-table>
        </div>
      </template>
    </vxe-modal>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { VXETable, VxeTableInstance, VxeColumnPropTypes, VxeFormPropTypes, VxeTableEvents } from 'vxe-table'
import { coachPost, coachGet, coachDel, schoolGet, coach1Get, coach2Get } from "../../../api/coachmange"
interface RowVO {
  id: number;
  name: string;
  phone: string;
  schoolName: string;
  coachintro: string;
  level: string;
  time: string;
  object: string;
  objectId: string;
  carType: string;
}

const xTable = ref<VxeTableInstance<RowVO>>();

const formData = reactive({
  name: "",
  phone: "",
  schoolName: "",
  object: "",
  level: "",
  time: "",
  coachintro: "",
  checkedList: [] as any[],
  carType: "",
});

const showEdit = ref(false);
const selectRow = ref<RowVO | null>();
const tableData = ref<RowVO[]>([]);
const filterName = ref("");
const list = ref<RowVO[]>([]);
const levelOptions = ref([
  {
    label: "铜牌教练",
    value: "铜牌教练",
  },
  {
    label: "银牌教练",
    value: "银牌教练",
  },
  {
    label: "金牌教练",
    value: "金牌教练",
  },
]);
const carList = ref<any>([
  { carType: "A1", objectId: "A1" },
  { carType: "C1", objectId: "C1" },
]);

// carGet().then(()=>{

// })

const schoolList = ref<any>([]);
schoolGet().then((res) => {
  schoolList.value = res.data.results;
});
const levelList = ref([
  { label: "铜牌教练", value: "铜牌教练" },
  { label: "银牌教练", value: "银牌教练" },
  { label: "金牌教练", value: "金牌教练" },
]);
const objectList = ref([
  { label: "科目二", value: "科目二" },
  { label: "科目三", value: "科目三" },
]);

const formRules = reactive<VxeFormPropTypes.Rules>({
  name: [{ required: true, message: "请输入名字" }],
  phone: [{ required: true, message: "请输入手机号码" }],
  object: [{ required: true, message: "请选择科目" }],
});

const formatterLevel: VxeColumnPropTypes.Formatter<RowVO> = ({ cellValue }) => {
  const item = levelList.value.find((item) => item.value === cellValue);
  return item ? item.label : "";
};

const stuShow = ref<boolean>(false);
const stuList = ref([]);
const stuCount = ref<number>();
const handleDetail = (row: RowVO) => {
  stuShow.value = true;
  console.log("detail", row);
  if (row.object == "科目二") {
    console.log("这里查coach1");
    coach1Get(row.objectId).then((res: any) => {
      console.log("查为coach1的学生数据", res);
      stuList.value = res.data.results;
      stuCount.value = res.data.results.length;
    });
  } else {
    console.log("这里查coach2");
    coach2Get(row.objectId).then((res: any) => {
      console.log("查为coach2的学生数据", res);
    });
  }
};

const insertEvent = () => {
  Object.assign(formData, {
    name: "",
    phone: "",
    schoolName: "",
    object: "",
    time: "",
    level: "",
    checkedList: [],
    coachintro: "",
    address: "",
    carType: "",
  });
  selectRow.value = null;
  showEdit.value = true;
};

const editEvent = (row: RowVO) => {
  Object.assign(formData, row);
  selectRow.value = row;
  showEdit.value = true;
};

const cellDBLClickEvent: VxeTableEvents.CellDblclick<RowVO> = ({ row }) => {
  editEvent(row);
};

const searchEvent = () => {
  const filterVal = String(filterName.value).trim().toLowerCase();
  if (filterVal) {
    const filterRE = new RegExp(filterVal, 'gi')
    const searchProps = ['name', 'id', 'phone', 'schoolName', 'coachintro', 'string',
      'level',
      'time',
      'checkedList',
      'object',
      'objectId']
    const rest = tableData.value.filter((item:any) => searchProps.some(key => String(item[key]).toLowerCase().indexOf(filterVal) > -1))
    list.value = rest.map(row => {
      const item: any = Object.assign({}, row)
      searchProps.forEach(key => {
        // item[key] = String(item[key]).replace(filterRE, match => `<span class="keyword-lighten">${match}</span>`)
        item[key] = String(item[key]).replace(filterRE, (match) => `${match}`);
      });
      return item;
    });
  } else {
    list.value = tableData.value;
  }
};

const removeEvent = async (row: RowVO) => {
  const type = await VXETable.modal.confirm("您确定要删除该数据?");
  console.log("row的数据", row);

  if (type === "confirm") {
    const $table = xTable.value;
    coachDel(row.objectId).then(() => {
      // console.log("删除了", row.objectId);
      VXETable.modal.message({ content: "删除成功", status: "success" });
    });
    if ($table) {
      $table.remove(row);
    }
  }
};

const submitEvent = (data: any) => {
  coachPost(data.data).then(() => {
    // console.log("新增成功", res);
    const $table = xTable.value;
    if ($table) {
      // showEdit.value = false
      searchEvent();
      // console.log("value", data.data);
      if (selectRow.value) {
        VXETable.modal.message({ content: "保存成功", status: "success" });
        Object.assign(selectRow.value, formData);
      } else {
        VXETable.modal.message({ content: "新增成功", status: "success" });
        $table.insert({ ...formData });
      }
    }
  });
};
coachGet().then((res) => {
  const list: RowVO[] = res.data.results;
  tableData.value = list;
  searchEvent();
});
</script>

<style scoped >
.stubutton {
  background: #febc11;
  color: white;
}
</style>